<template>
	<view>
		<u-toast ref="uToast"></u-toast>
		<u-navbar :placeholder="true" :autoBack="true" title="提交订单"></u-navbar>
		<view class="margin-top-xs bg-white padding-sm">
			<view class="flex justify-between align-center">
				<text class="text-grey">所属门店</text>
				<text class="text-black text-df text-bold">{{params.storeName}}</text>
			</view>
			<u-line dashed margin="10px 0px 10px 0"></u-line>
			<view class="flex align-start justify-start">
				<image :src="params.roomImage" style="width: 100px;height: 100px;border-radius: 10px;"></image>
				<view class="margin-left-sm">
					<view class="text-lg text-bold">{{params.roomName}}</view>
				</view>
			</view>
		</view>
		<view class="margin-top-xs bg-white padding-sm">
			<view class="flex align-center justify-between">
				<text>开始时间</text>
				<text>{{params.beginTime}}</text>
			</view>
			<u-line dashed margin="10px 0px 10px 0"></u-line>
			<view class="flex align-center justify-between">
				<text>结束时间</text>
				<text>{{params.endTime}}</text>
			</view>
			<u-line dashed margin="10px 0px 10px 0"></u-line>
			<view class="flex align-center justify-between">
				<text>共计时长</text>
				<view>
					<text>共{{params.allhoure}}小时</text>
				</view>
			</view>
			<u-line dashed margin="10px 0px 10px 0"></u-line>
			<view class="flex align-center justify-between">
				<text>共计费用</text>
				<view v-if="isMember" class="flex flex-direction align-end">
				<!-- 	<text class="text-gray text-sm text-price"
						style="text-decoration: line-through; ">{{needPrice/100}}</text> -->
						
					<text class="margin-top-xs text-tea text-bold text-price">{{params.needPrice/100}}</text>
				</view>
				<view v-else>
					<text class="text-price">{{params.needPrice}}</text>
				</view>
			</view>
		</view>
		<view class="margin-top-xs bg-white padding-sm">
			<view class="flex align-center justify-between">
				<text>抖音券码</text>
				<view v-if="changeYHQPackage.skuId" class="flex flex-direction align-end">
					<view class="line-blue" @click="gotoChanegPackage">
						<text>{{changeYHQPackage.dyProductInfo.productName}}</text>
						<text class="cuIcon-right text-blue"></text>
					</view>
					<!-- <text class="text-sm text-gray margin-top-xs">减免金额：{{params.jianMianMoney}}</text> -->
					<text class="text-sm text-gray margin-top-xs" style="text-decoration: underline;"
						@click="cancelUsePackage()">取消使用卡券</text>
				</view>
				<view v-else class="line-blue" @click="gotoChanegPackage">
					<text>选择卡券</text>
					<text class="cuIcon-right text-blue"></text>
					<!-- <text class="cuIcon-scan text-tea" style="font-size: 40rpx;" @click="scanCode"></text> -->
				</view>
			</view>
		<!-- 	<u-line dashed margin="10px 0px 10px 0"></u-line>
			<view class="flex align-center justify-between">
				<text>优惠券</text>
				<view class="line-blue" @click="gotoChanegPackage">
					<text>暂无可用优惠券</text>
					<text class="cuIcon-right text-blue"></text>
				</view>
			</view> -->
		</view>
		<view class="margin-top-xs bg-white padding-sm">
			<view>温馨提示</view>
			<view class="margin-top-xs text-sm" v-html="storeDetalis.store.PayReminder"></view>
		</view>
		<view v-show="!isMember" @click="makeMember"
			class="margin-sm  padding-xl flex align-center justify-between radius  bg-white">
			<view class="flex align-center">
				<text class="cuIcon-vip" style="color: #89674C;font-size: 30px;"></text>
				<text style="color: #89674C;" class="text-bold margin-left-xs">成为会员立享优惠</text>
			</view>
			<view>
				<text style="color: #89674C;" class="text-bold">去了解</text>
				<text class="cuIcon-right" style="color: #89674C;"></text>
			</view>
		</view>
		<view class="flex align-center justify-center u-safe-bottom margin-top-lg"
			style="bottom: 0px;left: 0px;width: 100%;">
			<button @click="submitOrder" class="bg-tea cu-btn u-safe-bottom margin-bottom-lg"
				style="width: 94%;height: 80rpx;">
				立即支付
			</button>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				params: {
					storeId: '', //店铺Id,
					roomId: '', //房间Id,
					beginTime: '', //开始时间,
					endTime: '', //结束时间
					allhoure: '', //共多少小时
					roomImage: '',
					storeName: '',
					roomName: '',
					needPrice:'',
					jianMianMoney: 0,
					code:''
				},
				roomId:'',
				startTime:'',
				endTime:'',
				memberPrice: '', //会员优惠完后的金额
				isMember: null,
				balance: '', //余额
				out_trade_no: '',
				userPackage: {
					canUse: [], //可用的卡券，
					canNotUse: [], //不可用的卡券
				},
				changeYHQPackage: {
					StorePackage: {
						Id: '',
						Title: ''
					}
				}, //选择的优惠券
				storeDetalis: {},
			}
		},
		onLoad(params) {
			this.params = params;
			this.endTime= params.endTime;
			this.startTime = params.startTime;
			this.roomId = params.roomId;
			// this.getStoreDetalis();
			this.getOrderPrice2();
		},
		created() {
			const vm = uni.getStorageSync('UserInfo');
			this.isMember = vm.user?.isMember;
			
			this.checkUserIsVip();
			
		},

		methods: {


			//跳转到卡券选择页面
			gotoChanegPackage() {
				uni.setStorageSync('UserPackage', this.userPackage);
				let that = this;

				let params = 'storeId=' + this.params.storeId + '&roomId=' + this.params.roomId +'&startTime=' + this.params.startTime +
					'&endTime=' + this.params.endTime 
				uni.navigateTo({
					url: '/pagesA/store/canusepackage?'+ params,
					events: {
						acceptDataFromOpenedPage: function(data) {
							that.changeYHQPackage = data;
							that.getOrderPrice();
						},
					}
				})
			},
			//取消使用卡券
			cancelUsePackage() {
				this.changeYHQPackage = {
					StorePackage: {
						Id: '',
						Title: ''
					}
				};
				this.getOrderPrice2();
			},
			//成为会员
			makeMember() {
				uni.navigateTo({
					url: '/pagesA/member/introduce'
				})
			},
			//判断一下用户是否是vip
			checkUserIsVip() {
				this.isMember = true;
				console.log("是否会员，会员余额，暂时不做");
				// this.getUserCanUsePackage();
				// uni.$u.http.post('/Customer/CheckUserIsVip').then(res => {
				// 	// this.isMember = res.data.isMember; //是否为会员
				// 	// this.balance = res.data.balance; //会员余额
				// 	// //选择用户可用的卡券、优惠券
				// 	this.getUserCanUsePackage();

				// });
			},
			//获取用户可用的优惠券、卡券
			getUserCanUsePackage() {
				console.log("优惠券暂时不做");
				
				let data = {
					storeId: this.params.storeId, //店面Id,
					roomId: this.params.roomId, //房间Id,
					startTime: this.params.startTime, //开始时间
					endTime: this.params.endTime, //结束时间
				};
				uni.$u.http.post('/rest/douyin/avaiCoupons', data).then(res => {
					this.userPackage = res.data;
					if (res.data.length > 0) {
						this.changeYHQPackage = res.data[0];
					} else {
						this.changeYHQPackage = {
							StorePackage: {
								Id: '',
								Title: ''
							}
						};
					}
					console.log("changeYHQPackage",this.changeYHQPackage);
					this.getOrderPrice();
				})
			},
			getOrderPrice2(){
				let data = {
					// storeId: this.params.storeId, //店面Id,
					roomId: this.roomId, //房间Id,
					startTime: this.startTime, //开始时间
					endTime: this.endTime, //结束时间
					mealid: this.params.changeMealsId,
					pOrderNo: this.params.pOrderNo,
					// changYHQId: changYHQId,
				};
				
				// uni.showLoading();
				uni.$u.http.post('/rest/api/placeOrder', data).then(res => {
					this.params.needPrice = res.data.needPrice; //实际价格
					// this.memberPrice = res.data.memberPrice; //会员价格
					this.params.allhoure = res.data.totalHours; //总时长
					this.params.orderNo = res.data.orderNo;
					this.params.endTime = res.data.endTime;
					this.params.beginTime = res.data.beginTime;
					this.params.roomId = res.data.roomId;
					// this.params.jianMianMoney = res.data.jianMianMoney; //减免金额
				});
			},
			//获取工单实际消费
			getOrderPrice() {
				const changYHQId = this.changeYHQPackage.orderId ?? ''; //选择的优惠券返回
				
				let data = {
					// storeId: this.params.storeId, //店面Id,
					roomId: this.params.roomId.toString(), //房间Id,
					startTime: this.params.startTime, //开始时间
					endTime: this.params.endTime, //结束时间
					mealid: this.params.changeMealsId,
					pOrderNo: this.params.pOrderNo,
					orderId: changYHQId,
				};
				
				
				uni.$u.http.post('/rest/api/checkCoupon', data).then(res => {

					if (res.resultCode==2){
						this.$refs.uToast.show({
							message: res.resultMsg,
							type: 'error',
							position: 'center'
						});
						this.cancelUsePackage();
					}else{
					this.params.needPrice = res.data.needPrice; //实际价格
					// this.memberPrice = res.data.memberPrice; //会员价格
					this.params.allhoure = res.data.totalHours; //总时长
					// this.params.orderNo = res.data.orderNo;
					this.params.endTime = res.data.endTime;
					this.params.beginTime = res.data.beginTime;
					this.params.roomId = res.data.roomId;
					this.params.couponPayAmount = res.data.couponPayAmount;
					this.params.code = res.data.code
					// this.params.jianMianMoney = res.data.jianMianMoney; //减免金额
					}
				});
			},
			//创建订单
			submitOrder() {
				//开始创建订单，返回一个工单
				uni.showLoading({
					title: '创建订单中',
				});

				const changYHQId = this.changeYHQPackage.orderId ?? ''; 
				let data = {
					roomId: this.roomId, //房间Id,
					beginTime: this.params.beginTime, //开始时间
					endTime: this.params.endTime, //结束时间
					totalFee: this.params.needPrice,
					orderNo: this.params.orderNo,
					totalHours: this.params.allhoure,
					couponPayAmount: this.params.couponPayAmount,
					orderId: changYHQId,
					code: this.params.code
				};
				this.confirmPay(data);
			},
			
			//立即支付
			confirmPay(data) {
				uni.showLoading();
				uni.$u.http.post('/rest/wxpay/jsapi/corder', data).then(res => {
					
					if (res.resultCode==0) {
						this.turnUpWxPay(res);
						
					}else if(res.resultCode==1){
						uni.hideLoading();
						this.$refs.uToast.show({
								message: '支付成功！',
								type: 'success',
								position: 'top'
							});
						uni.redirectTo({
							url: '/pagesB/layout/orderpaysuc?orderId=' + this.params.orderNo
						})
							return;
					}else{
						uni.showToast({
							title: res.resultMsg,
							icon: 'none'
						})
						return;
					}
					
				})
			},
			turnUpWxPay(res) {
				let that = this;
				this.out_trade_no = res.data.out_trade_no; //支付订单
				uni.requestPayment({
					provider: 'wxpay', //支付类型-固定值
					timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
					nonceStr: res.data.nonceStr, // 随机字符串
					package: res.data.package, // 固定值
					signType: res.data.signType, //固定值
					paySign: res.data.paySign, //签名
					success: function(res) {
						uni.showLoading({
							title: '支付结果查询中',
							duration: 30000
						})
						that.changeOrderStatusTotal = 0;
						that.timeIntervalId = setInterval(that.callBackPayResult, 3000);
					},
					fail: function(err) {
						console.log(err);
						let emsg = '支付失败';
						if (err.errMsg.indexOf('fail cancel') != -1) {
							emsg = '用户取消支付';
						}
						uni.showToast({
							icon: 'none',
							title: emsg
						})
					}
				});
			},
			//通知后端手动查询订单结果
			callBackPayResult() {
				this.changeOrderStatusTotal++;
				if (this.changeOrderStatusTotal >= 10) {
					clearInterval(this.timeIntervalId);
					uni.hideLoading();
					this.$refs.uToast.show({
						message: '查询支付结果超时！',
						type: 'error',
						position: 'top'
					});
					return;
				}
				//params.storeId
				uni.$u.http.post('/rest/wxpay/order/info', {
					out_trade_no: this.out_trade_no
				}).then(res => {
					if (res.data.orderStatus == "支付成功") {
						clearInterval(this.timeIntervalId);
						uni.hideLoading();
						this.$refs.uToast.show({
							message: '支付成功！',
							type: 'success',
							position: 'top'
						});
					uni.redirectTo({
						url: '/pagesB/layout/orderpaysuc?orderId=' + this.out_trade_no
					})
						return;
					}else{
						uni.showLoading({
							title: '支付结果查询中',
							duration: 30000
						})
					}
				})
			},
			goBack() {
				uni.navigateBack();
			},

		}
	}
</script>

<style scoped>

</style>